package com.dwxt.parabolic.controller;

import com.dwxt.common.exception.AesException;
import com.dwxt.common.util.wxUtil.CheckUtil;
import com.dwxt.parabolic.service.BindService;
import com.dwxt.parabolic.utils.ReplyTextMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@RequestMapping("/parabolic/authentication")
@RestController
public class AuthenticationController {

    @Autowired
    private BindService bindService;

    /**
     * 微信消息解析
     */
    @GetMapping("/wx")
    public void  getCheck(HttpServletRequest request, HttpServletResponse response) throws AesException, IOException {
        // get方法主要处理公众号接入部分
        String signature=request.getParameter("signature");
        String timestamp=request.getParameter("timestamp");
        String nonce=request.getParameter("nonce");
        String echostr=request.getParameter("echostr");
        PrintWriter pWriter=response.getWriter();
        if(CheckUtil.checkSignature(signature, timestamp, nonce)) {
            pWriter.print(echostr);
            pWriter.close();
        }
    }

    /**
     * 微信消息解析
     */
    @PostMapping("/wx")
    public void  getMsg(HttpServletRequest request, HttpServletResponse response) throws AesException, IOException {
        //接受微信服务器发送过来的XML形式的消息
        InputStream in=request.getInputStream();
        BufferedReader reader=new BufferedReader(new InputStreamReader(in,"UTF-8"));
        String sReqData="";
        String itemStr="";//作为输出字符串的临时串，用于判断是否读取完毕
        while((itemStr=reader.readLine())!=null){
            sReqData+=itemStr;
        }
        in.close();
        reader.close();

        System.out.println("收到消息："+sReqData);
        //防止中文乱码
        response.setCharacterEncoding("UTF-8");
        //接受微信消息并执行业务
        bindService.replyMessage(sReqData,response);
    }
}
